package com.ktgj.customer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import com.ktgj.common.core.constant.ConponStatus;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.vo.CouponVo;
import com.ktgj.customer.domain.vo.HotelCouponVo;
import com.ktgj.customer.mapper.CouponServicesMapper;
import com.ktgj.customer.mapper.CustomerRightdetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.customer.mapper.CouponMapper;
import com.ktgj.customer.service.ICouponService;

/**
 * 优惠券信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-03
 */
@Service
public class CouponServiceImpl implements ICouponService {
    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CustomerRightdetailMapper customerRightdetailMapper;

    @Autowired
    private CouponServicesMapper couponServicesMapper;

    /**
     * 查询优惠券信息
     *
     * @param couponId 优惠券信息ID
     * @return 优惠券信息
     */
    @Override
    public Coupon selectCouponById(Long couponId) {
        return couponMapper.selectCouponById(couponId);
    }

    /**
     * 查询优惠券信息列表
     *
     * @param coupon 优惠券信息
     * @return 优惠券信息
     */
    @Override
    public List<Coupon> selectCouponList(Coupon coupon) {
        return couponMapper.selectCouponList(coupon);
    }

    /**
     * 新增优惠券信息
     *
     * @param coupon 优惠券信息
     * @return 结果
     */
    @Override
    public int insertCoupon(Coupon coupon) {
        return couponMapper.insertCoupon(coupon);
    }

    /**
     * 修改优惠券信息
     *
     * @param coupon 优惠券信息
     * @return 结果
     */
    @Override
    public int updateCoupon(Coupon coupon) {
        return couponMapper.updateCoupon(coupon);
    }

    /**
     * 批量删除优惠券信息
     *
     * @param couponIds 需要删除的优惠券信息ID
     * @return 结果
     */
    @Override
    public int deleteCouponByIds(Long[] couponIds) {
        return couponMapper.deleteCouponByIds(couponIds);
    }

    /**
     * 删除优惠券信息信息
     *
     * @param couponId 优惠券信息ID
     * @return 结果
     */
    @Override
    public int deleteCouponById(Long couponId) {
        return couponMapper.deleteCouponById(couponId);
    }

    /**
     * 根据金额推荐最优优惠券
     *
     * @param customerId
     * @return
     */
    @Override
    public CouponDto queyUserCoupon(Long customerId, BigDecimal money) {
        String rightdetailType = CustomerConstants.rightTypeCoupon.getValue();
        String couponStatus = CustomerConstants.unexecuted.getValue();
        List<CouponDto> coupons = couponMapper.queyUserCoupon(customerId, rightdetailType, couponStatus);

        List<CouponDto> fullMinus = coupons.stream().filter(item -> item.getCouponType().equals(CustomerConstants.CouponTypeFullMinus.getValue())).collect(Collectors.toList());//满减
        List<CouponDto> cashCoupon = coupons.stream().filter(item -> item.getCouponType().equals(CustomerConstants.CouponTypeCashCoupon.getValue())).collect(Collectors.toList());//代金
        List<CouponDto> discount = coupons.stream().filter(item -> item.getCouponType().equals(CustomerConstants.CouponTypeDiscount.getValue())).collect(Collectors.toList());//折扣
        CouponDto full = null;
        for (CouponDto minus : fullMinus) {
            BigDecimal maxPrice = new BigDecimal(minus.getCouponMaxprice());
            if (money.doubleValue() >= maxPrice.doubleValue()) {
                if (full == null)
                    full = minus;
                else if (minus.getCouponPrice() > full.getCouponPrice())
                    full = minus;
            }
        }
        CouponDto cash = null;
        for (CouponDto minus : cashCoupon) {
            if (cash == null)
                cash = minus;
            else if (minus.getCouponPrice() > cash.getCouponPrice())
                cash = minus;
        }
        CouponDto dis = null;
        for (CouponDto coupon : discount) {
            if (dis == null) {
                dis = coupon;
                continue;
            }
            BigDecimal price = new BigDecimal(coupon.getCouponDiscount());
            BigDecimal divide = price.divide(new BigDecimal(100));
            BigDecimal countPrice = money.multiply(divide);

            BigDecimal disPrice = new BigDecimal(dis.getCouponDiscount());
            BigDecimal disDivide = disPrice.divide(new BigDecimal(100));
            BigDecimal discountPrice = money.multiply(disDivide);
            if (countPrice.compareTo(discountPrice) == -1)
                dis = coupon;
        }
        CouponDto coupon = null;
        if (full != null && cash != null) {
            if (full.getCouponPrice() > cash.getCouponPrice())
                coupon = full;
            else
                coupon = cash;
        } else {
            if (full != null)
                coupon = full;
            else if (cash != null)
                coupon = cash;
        }
        if (dis != null) {
            BigDecimal decimal = new BigDecimal(dis.getCouponDiscount()).divide(new BigDecimal(100));
            decimal = money.multiply(decimal);
            if (coupon != null) {
                if (money.subtract(new BigDecimal(coupon.getCouponPrice().longValue())).compareTo(decimal) == 1)
                    coupon = dis;
            } else {
                coupon = dis;
            }

        }
        return coupon;
    }

    /**
     * 优惠券使用记录列表
     */
    @Override
    public List<CouponVo> couponRecord(Long customerId, String type) {
        List<Coupon> couponList;
        if (type.equals("all"))
        {
            couponList = couponMapper.couponRecord(customerId, null);
        }else
        {
            couponList = couponMapper.couponRecord(customerId, type);
        }
        List<CouponVo> couponVoList = new CopyOnWriteArrayList<>();
        for (Coupon coupon : couponList) {
//            CustomerRightdetail customerRightdetail = customerRightdetailMapper.equityStatus(customerId, coupon.getCouponId());
//            if (customerRightdetail.getRightdetailState().equals(type)) {
                CouponVo couponVo = new CouponVo();
                couponVo.setCouponId(coupon.getCouponId());
                if (coupon.getCouponType().equals("discount")) {
                    couponVo.setContent("使用规则 享" + coupon.getCouponDiscount() / 10 + "." + coupon.getCouponDiscount() % 10 + "折优惠");
                    couponVo.setCouponDiscount(coupon.getCouponDiscount() / 10 + "." + coupon.getCouponDiscount() % 10);
                } else if (coupon.getCouponType().equals("fullMinus")) {
                    couponVo.setContent("使用规则 满" + coupon.getCouponMaxprice() + "抵" + coupon.getCouponPrice());
                    couponVo.setCouponMaxprice(coupon.getCouponMaxprice().toString());
                    couponVo.setCouponPrice(coupon.getCouponPrice().toString());
                }  else if (coupon.getCouponType().equals("cashCoupon")) {
                    couponVo.setContent("使用规则 选择相应商品，加购支付");
                    couponVo.setCouponPrice(coupon.getCouponPrice().toString());
                }
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String date = format.format(coupon.getInvalidTime());
                couponVo.setInvalidTime("有效期 " + date + "前");
                couponVo.setInvalidTime("有效期 " + date + "前");
                couponVo.setCouponType(coupon.getCouponType());
                couponVo.setName(coupon.getCouponName());
                String count = null;
                List<CouponServices> couponServicesList = couponServicesMapper.selectServices(coupon.getCouponId());
                String scope = "";
                for (CouponServices couponServices : couponServicesList) {
                    scope = scope + "," + couponServices.getServiceType();
                }
                couponVo.setScope(scope);
                couponVoList.add(couponVo);
//            }
        }
        return couponVoList;
    }

    /**
     * 优惠券列表
     */
    @Override
    public List<CouponVo> CustomerRightdetailList(Long customerId, String type) {
        switch (type) {
            case "all":
                type = "";
                break;
            case "discount":
                type = "折扣券";
                break;
            case "cashCoupon":
                type = "兑换券";
                break;
            case "coupon":
                type = "优惠券";
                break;
        }
        List<CustomerRightdetail> customerRightdetailList = customerRightdetailMapper.CustomerRightdetailList(customerId, type);
        List<CouponVo> couponVoList = new CopyOnWriteArrayList<>();
        if (customerRightdetailList != null && customerRightdetailList.size() > 0)
        {
            for (CustomerRightdetail customerRightdetail : customerRightdetailList) {
                Coupon temporaryCoupon = couponMapper.couponList(customerRightdetail.getRightdetailTypeid());
                if (temporaryCoupon.getCouponStatus().equals("normal")) {
                    CouponVo couponVo = new CouponVo();
                    couponVo.setCouponId(customerRightdetail.getCustomerRightdetailId());
                    if (temporaryCoupon.getCouponDiscount() != null) {
                        couponVo.setContent("使用规则 享" + temporaryCoupon.getCouponDiscount() / 10 + "." + temporaryCoupon.getCouponDiscount() % 10 + "折优惠");
                        couponVo.setCouponDiscount(temporaryCoupon.getCouponDiscount() / 10 + "." + temporaryCoupon.getCouponDiscount() % 10);
                        couponVo.setName(temporaryCoupon.getCouponName());
                    } else if (temporaryCoupon.getCouponMaxprice() != null) {
                        couponVo.setContent("使用规则 满" + temporaryCoupon.getCouponMaxprice() + "抵" + temporaryCoupon.getCouponPrice());
                        couponVo.setCouponMaxprice(temporaryCoupon.getCouponMaxprice().toString());
                        couponVo.setCouponPrice(temporaryCoupon.getCouponPrice().toString());
                        couponVo.setName(temporaryCoupon.getCouponName());
                    } else if (temporaryCoupon.getCouponPrice() != null) {
                        couponVo.setContent("使用规则 选择相应商品，加购支付");
                        couponVo.setCouponPrice(temporaryCoupon.getCouponPrice().toString());
                        couponVo.setName(temporaryCoupon.getCouponName());
                    } else {
                        couponVo.setContent(temporaryCoupon.getCouponDesc());
                        couponVo.setName(temporaryCoupon.getCouponName());
                    }
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    String date = format.format(temporaryCoupon.getInvalidTime());
                    couponVo.setInvalidTime("有效期 " + date + "前");
                    couponVo.setCouponType(temporaryCoupon.getCouponType());
                    List<CouponServices> couponServicesList = couponServicesMapper.selectServices(customerRightdetail.getRightdetailTypeid());
                    Set<String> set = new HashSet<>();
                    if (couponServicesList != null && couponServicesList.size() > 0) {
                        for (CouponServices couponServices : couponServicesList) {
                            if (set.size() > 0) {
                                if (set.add(couponServices.getAppropriateType())) {
                                    couponVo.setScope("homePage");
                                    break;
                                } else
                                    couponVo.setScope(couponServices.getAppropriateType());
                            } else {
                                set.add(couponServices.getAppropriateType());
                                couponVo.setScope(couponServices.getAppropriateType());
                            }
                        }
                        couponServicesList.forEach(coupon -> {
                            couponVo.getCouponService().add(coupon.getAppropriateType());
                        });
                    }
                    couponVoList.add(couponVo);
                }
            }
        }
        return couponVoList;
    }

    @Override
    public Coupon couponById(Long couponId) {
        return couponMapper.couponById(couponId);
    }

    @Override
    public CouponBO couponByCustomerRightDetailId(Long customerRightDetailId) {
        return couponMapper.couponByCustomerRightDetailId(customerRightDetailId);
    }

    /**
     * 查询指定业务线的优惠券信息
     * */
    @Override
    public List<CouponVo> businessCoupon(String businessType, Long customerId) throws Exception {
        String type = "all";
        if (customerId != null && customerId != 0){
            List<CouponVo> couponVoList = CustomerRightdetailList(customerId, type);
            if (couponVoList != null && couponVoList.size() > 0){
                List<CouponVo> couponVos = new ArrayList<>();
                for (CouponVo couponVo : couponVoList) {
                    CouponServices couponServices = couponServicesMapper.selectCouponServicesByCouponId(couponVo.getCouponId());
                    if (couponServices != null){
                        if (businessType.equals(couponServices.getAppropriateType())){
                            couponVos.add(couponVo);
                        }
                    }
                    else {
                        throw new Exception("未查到数据");
                    }
                }
                return couponVos;
            }
            else {
                return null;
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 酒店优惠券列表
     * */
    @Override
    public List<HotelCouponVo> couponList(String type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date());
        List<Coupon> couponList = couponMapper.hotelCouponList(type, date);
        if (couponList != null && couponList.size() > 0){
            List<HotelCouponVo> hotelCouponVoList = new ArrayList<>();
            for (Coupon coupon : couponList) {
                HotelCouponVo hotelCouponVo = new HotelCouponVo();
                hotelCouponVo.setCouponId(coupon.getCouponId());
                if (coupon.getCouponDiscount() != null){
                    hotelCouponVo.setCouponName((coupon.getCouponDiscount() * 10) + "折");
                }
                else if (coupon.getCouponMaxprice() != null){
                    hotelCouponVo.setCouponName("满" + coupon.getCouponMaxprice() + "抵" + coupon.getCouponPrice());
                }
                else if (coupon.getCouponPrice() != null){
                    hotelCouponVo.setCouponName(coupon.getCouponPrice().toString());
                }
                hotelCouponVoList.add(hotelCouponVo);
            }
            return hotelCouponVoList;
        }
        else {
            return null;
        }
    }
}
